package com.ruibang.glass.equipment.controller;

import com.alibaba.excel.util.DateUtils;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.ruibang.glass.common.constants.CommonErrorCode;
import com.ruibang.glass.equipment.constant.Constants;
import com.ruibang.glass.equipment.constant.EquipmentErrorCode;
import com.ruibang.glass.equipment.domain.req.device.DeviceAllPageReq;
import com.ruibang.glass.equipment.entity.device.InstrumentRegister;
import com.ruibang.glass.equipment.entity.device.ScrapReport;
import com.ruibang.glass.equipment.service.InstrumentRegisterService;
import com.teaming.cloud.framework2.common.exception.ServiceException;
import com.teaming.cloud.framework2.common.model.ResultBody;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
/**
 * <p>
 *测量体系/仪表台账
 * </p>
 *
 * @author mameng
 * @since 2024-03-20
 */
@RestController
@RequestMapping("/api/equipment/instrument/register")
@Api(value = "测量体系/仪表台账")
public class InstrumentRegisterController {
    @Autowired
    private InstrumentRegisterService instrumentRegisterService;

    @PostMapping("list")
    @ApiOperation(value = "检修工作单列表", response = ResultBody.class)
    public ResultBody getBoilerList(@RequestBody DeviceAllPageReq deviceAllPageRea) {
        return ResultBody.success(instrumentRegisterService.queryPage(deviceAllPageRea));
    }

    @PostMapping("addOrUpdateCheck")
    @ApiOperation(value = "修改添加", response = ResultBody.class)
    public ResultBody addChild(@RequestBody InstrumentRegister repairWorkOrder) {
        return ResultBody.success(instrumentRegisterService.updateOrAddById(repairWorkOrder));
    }


    //
    @PostMapping("deleteAll")
    @ApiOperation(value = "删除", response = ResultBody.class)
    public ResultBody deleteAll(@RequestBody InstrumentRegister repairWorkOrder) {
        if (CollectionUtils.isNotEmpty(repairWorkOrder.getIds())) {
            instrumentRegisterService.lambdaUpdate().set(InstrumentRegister::getIsDelete, Constants.ONE_STR).in(InstrumentRegister::getId, repairWorkOrder.getIds()).update();
        }
        if (StringUtils.isNoneBlank(repairWorkOrder.getId())) {
            instrumentRegisterService.lambdaUpdate().set(InstrumentRegister::getIsDelete, Constants.ONE_STR).eq(InstrumentRegister::getId, repairWorkOrder.getId()).update();
        }
        return ResultBody.success();
    }


    @PostMapping("getOne")
    @ApiOperation(value = "查看详情", response = ResultBody.class)
    public ResultBody getOne(@RequestBody InstrumentRegister repairWorkOrder) {
        return ResultBody.success(instrumentRegisterService.getById(repairWorkOrder.getId()));
    }


    @PostMapping("addBfBb")
    @ApiOperation(value = "新增报废报表", response = ResultBody.class)
    public ResultBody addBfBb(@RequestBody InstrumentRegister repairWorkOrder) {
        instrumentRegisterService.addBfBb(repairWorkOrder);
        return ResultBody.success();
    }

    @PostMapping("/export")
    @ApiOperation(value = "数据导出", response = ResultBody.class)
//    @FrequencyControl(time = 15, count = 2, target = FrequencyControl.Target.IP)
//    @FrequencyControl(time = 30, count = 5, target = FrequencyControl.Target.IP)
    public void export(@RequestBody DeviceAllPageReq machiningReq, HttpServletResponse response) {
        instrumentRegisterService.export(machiningReq, response);
    }

    // 导入
    @PostMapping("importExcel")
    @ApiOperation(value = "导入", response = ResultBody.class)
    public ResultBody importExcel(@RequestPart("files") MultipartFile file, HttpServletRequest request) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String contentType = file.getContentType();
        System.out.println("文件类型是===========" + contentType);
        String fileName = file.getOriginalFilename();
        System.out.println("文件名字是===========" + fileName);
        try {
//            if (!fileName.endsWith(".xlsx")) {
//                return ResultBody.fail(300, "文件格式不正确！请使用.Xlsx格式");
//            }
            if (file.isEmpty()) {
                return ResultBody.fail(310, "文件为空！");
            }
            //根据路径获取这个操作excel的实例
            XSSFWorkbook wb = new XSSFWorkbook(inputStream);
            //根据页面index 获取sheet页
            Sheet sheet = wb.getSheetAt(0);
            //获取sheet页共有多少行
            int totalRos = sheet.getPhysicalNumberOfRows();
            System.out.println("=========总行数为：" + totalRos);
            if (totalRos < 2) {
                return ResultBody.fail(300, "文件禁止为只有表头！");
            }
            for (int i = 1; i < totalRos; i++) {
                int lastCellNum = sheet.getRow(i).getLastCellNum();
                if (lastCellNum != 10) {
                    return ResultBody.fail(CommonErrorCode.MONITOR_DATA_EXPORT_IN_FAIL.getCode(), CommonErrorCode.MONITOR_DATA_EXPORT_IN_FAIL.message);
                }
                //sheet.getRow(i).getCell(j).toString()
                System.out.println("=========第" + i + "行的数据如下：=========");
                InstrumentRegister instrumentRegister = new InstrumentRegister();
                instrumentRegister.setArea(sheet.getRow(i).getCell(0).toString());
                instrumentRegister.setNumber(sheet.getRow(i).getCell(1).toString());
                instrumentRegister.setName(sheet.getRow(i).getCell(2).toString());
                instrumentRegister.setType(sheet.getRow(i).getCell(3).toString());
                instrumentRegister.setLevel(sheet.getRow(i).getCell(4).toString());
                instrumentRegister.setCalibrationDate(DateUtils.parseDate(sheet.getRow(i).getCell(5).toString()));
                instrumentRegister.setCalibrationPeriod((int)sheet.getRow(i).getCell(6).getNumericCellValue());
                instrumentRegister.setUnit(sheet.getRow(i).getCell(7).toString());
                instrumentRegister.setResponsiblePerson(sheet.getRow(i).getCell(8).toString());
                instrumentRegister.setStatus(sheet.getRow(i).getCell(9).toString());
                instrumentRegisterService.save(instrumentRegister);
                System.out.println();
            }
        } catch (Exception e) {
            throw new ServiceException(EquipmentErrorCode.IMPORT_FILE_IS_FAILED.getCode(),EquipmentErrorCode.IMPORT_FILE_IS_FAILED.getMsg());
        }
        return ResultBody.success("成功");

    }

    @GetMapping("updateStatusByDayTime")
    @ApiOperation(value = "仪表台账状态跟新", response = ResultBody.class)
    public void updateStatusByDayTime() {
        instrumentRegisterService.updateStatusByDayTime();
    }

    @GetMapping("updateStatusByWeekTime")
    @ApiOperation(value = "仪表台账状态跟新", response = ResultBody.class)
    public void updateStatusByTime() {
        instrumentRegisterService.updateStatusByWeekTime();
    }

    @GetMapping("updateStatusByMonthTime")
    @ApiOperation(value = "仪表台账状态跟新", response = ResultBody.class)
    public void updateStatusByMonthTime() {
        instrumentRegisterService.updateStatusByMonthTime();
    }

    @GetMapping("updateStatusByYearTime")
    @ApiOperation(value = "仪表台账状态跟新", response = ResultBody.class)
    public void updateStatusByYearTime() {
        instrumentRegisterService.updateStatusByYearTime();
    }


}
